package com.nl.controller.web.service;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nl.controller.common.annotation.SystemServiceLog;
import com.nl.controller.common.exception.SmsException;
import com.nl.controller.common.service.CommonService;
import com.nl.controller.web.bean.SmsBaseStation;
import com.nl.controller.web.mapper.SmsBaseStationMapper;
import com.nl.controller.web.util.FileUtil;

import lombok.extern.slf4j.Slf4j;


@Service
@Slf4j
public class SmsBaseStationService {
    @Autowired
    private SmsBaseStationMapper smsBaseStationMapper;


    @Autowired
    private CommonService commonService;

    @SystemServiceLog(description = "根据条件查询基站信息", value = false)
    public PageInfo<SmsBaseStation> findSmsBaseStation(int page, int limit, String cityId, String mgrId,String mgrName) {
        Map<String, Object> map = new HashMap<>();
        map.put("cityId", cityId);
        map.put("mgrId", mgrId);
        map.put("name", mgrName);
        PageHelper.startPage(page, limit);
        List<SmsBaseStation> list = new ArrayList<>();
        try {
            list = smsBaseStationMapper.findSmsBaseStation(map);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询基站信息表");
            throw new SmsException("查询基站信息表出现异常");
        }
        PageInfo<SmsBaseStation> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @SystemServiceLog(description = "读取上传的的数据", value = false)
    public List<Integer> readCsv(String path, String mgrId, String cityId) throws IOException {
        List list;
        int stationNum = 0;//基站数量
        list = FileUtil.readCSV(path);
        List<String> regionList=new ArrayList();
        //add
        Map<String, Integer> map = new HashMap<String, Integer>();
        Integer regionId = smsBaseStationMapper.getMaxRegionId(cityId);
        for (int i = 0; i < list.size(); i++) {
        	String arr[] = list.get(i).toString().split(",");
        	String regionName = arr[0];
        	if (!map.containsKey(regionName)) {
				map.put(regionName,regionId);
				regionId++;
			}
        }
        //add end
        for (int i = 0; i < list.size(); i++) {
            SmsBaseStation baseStation = new SmsBaseStation();
            String arr[] = list.get(i).toString().split(",");
            baseStation.setCityId(cityId);
            baseStation.setId(mgrId);
            baseStation.setRegionId(map.get(arr[0])+"");
            baseStation.setRegionName(arr[0]);
            baseStation.setStationId(arr[1]);
            baseStation.setStationName(arr[2]);
            String unique = "1";
            try {
                unique = smsBaseStationMapper.checkBaseStation(baseStation);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("校验信息重复出现异常");
            }
            if (unique.equals("0")) {
                try {
                    smsBaseStationMapper.addSmsBaseStation(baseStation);
                    stationNum++;
                    if(!regionList.contains(arr[0])){
                        regionList.add(arr[0]);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("导入基站信息异常" + baseStation.getStateName());
                    throw new SmsException("导入基站信息");
                }
            }
        }
        List<Integer> result = new ArrayList();
        result.add(regionList.size());
        result.add(stationNum);
        map.clear();
        return result;
    }
    
    @SystemServiceLog(description = "导出项目基站数据", value = false)
    public JSONArray download(String cityId,String mgrId,String mgrName){
    	Map<String, Object> map = new HashMap<>();
        map.put("cityId", cityId);
        map.put("mgrId", mgrId);
        map.put("name", mgrName);
        List<SmsBaseStation> list = new ArrayList<>();
        try {
            list = smsBaseStationMapper.findSmsBaseStation(map);
            if(!"".equals(mgrId)&&null!=mgrId){
            	commonService.createSmsOperLog("7", mgrId,"导出项目基站信息："+mgrId, "0", "24");
            }else{
            	commonService.createSmsOperLog("7", "0","导出项目基站信息", "0", "24");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询基站信息表");
            if(!"".equals(mgrId)&&null!=mgrId){
            	commonService.createSmsOperLog("7", mgrId,"导出项目基站信息："+mgrId, "1", "24");
            }else{
            	commonService.createSmsOperLog("7", "0","导出项目基站信息", "1", "24");
            }
            throw new SmsException("查询基站信息表出现异常");
        }
        JSONArray jsonArray = JSONArray.parseArray(JSONArray.toJSONString(list));
        return jsonArray;
    }
    
    /**
     * desc:根据项目编号查询基站
     * @author syl
     * @Date 2019年9月3日 上午10:17:20
     * @param mgrId
     * @return
     */
    @SystemServiceLog(description = "根据项目编号查询基站", value = false)
    public List<SmsBaseStation> getStation(String mgrId){
    	Map<String, Object> map = new HashMap<>();
        map.put("mgrId", mgrId);
        List<SmsBaseStation> list = new ArrayList<>();
        try {
            list = smsBaseStationMapper.findSmsBaseStation(map);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询基站信息表");
            throw new SmsException("查询基站信息表出现异常");
        }
        return list;
    }
    
    /**
     * desc:根据项目编号插入复制的基站
     * @author syl
     * @Date 2019年9月3日 上午10:20:19
     * @param mgrId
     * @return
     */
    @Transactional
    @SystemServiceLog(description = "根据项目编号插入复制的基站", value = false)
    public int addCopyStation(String mgrId,List<SmsBaseStation> list){
        int result = 0 ;
        SmsBaseStation baseStation = null;
        try {
        	smsBaseStationMapper.deleteBaseStation(mgrId);
        	for (int i = 0; i < list.size(); i++) {
                baseStation = new SmsBaseStation();
                baseStation.setId(mgrId);
                baseStation.setRegionId(list.get(i).getRegionId());
                baseStation.setRegionName(list.get(i).getRegionName());
                baseStation.setStationId(list.get(i).getStationId());
                baseStation.setStationName(list.get(i).getStationName());
                baseStation.setCityId(list.get(i).getCityId());
                smsBaseStationMapper.addSmsBaseStation(baseStation);
                result++;
            }
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			e.printStackTrace();
            log.error("复制基站信息异常" + baseStation.getStateName());
            commonService.createSmsOperLog("3", mgrId,"插入基站信息表", "1", "21");
            throw new SmsException("插入基站信息");
		}
        return result;
    }
    @Transactional
    @SystemServiceLog(description = "读取上传的的数据(覆盖或追加)", value = false)
    public List<Integer> readCsvByImport(String path, String mgrId, String cityId,String flag) throws IOException {
        List list;
        int stationNum = 0;//基站数量
        list = FileUtil.readCSV(path);
        List<String> regionList=new ArrayList();
        try {
        	if ("importCover".equals(flag)) {
            	smsBaseStationMapper.deleteBaseStation(mgrId);
    		}
		} catch (Exception e) {
			e.printStackTrace();
            log.error("删除基站信息出现异常");
		}
        
        //add
        Map<String, Integer> map = new HashMap<String, Integer>();
        Integer regionId = smsBaseStationMapper.getMaxRegionId(cityId);
        //add end
        for (int i = 0; i < list.size(); i++) {
        	String arr[] = list.get(i).toString().split(",");
        	String regionName = arr[0];
        	if (!map.containsKey(regionName)) {
				map.put(regionName,regionId);
				regionId++;
			}
        }
        for (int i = 0; i < list.size(); i++) {
            SmsBaseStation baseStation = new SmsBaseStation();
            String arr[] = list.get(i).toString().split(",");
            String stationId=arr[1];
            String reg="[0-9]*";
            String[] sta= stationId.split(":");
            if(sta[0]!=null&&sta[1]!=null){
            	if(sta[0].matches(reg)&&sta[1].matches(reg)){
                	log.info("基站编码格式校验通过");
                	 baseStation.setCityId(cityId);
                     baseStation.setId(mgrId);
                     baseStation.setRegionId(map.get(arr[0])+"");
                     baseStation.setRegionName(arr[0]);
                     baseStation.setStationId(arr[1]);
                     baseStation.setStationName(arr[2]);
                     String unique = "1";
                     try {
                         unique = smsBaseStationMapper.checkBaseStation(baseStation);
                     } catch (Exception e) {
                         e.printStackTrace();
                         log.error("校验信息重复出现异常");
                     }
                     if (unique.equals("0")) {
                         try {
         					smsBaseStationMapper.addSmsBaseStation(baseStation);
                             stationNum++;
                             if(!regionList.contains(arr[0])){
                                 regionList.add(arr[0]);
                             }
                         } catch (Exception e) {
                         	TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                             e.printStackTrace();
                             log.error("导入基站信息异常" + baseStation.getStateName());
                             commonService.createSmsOperLog("3",mgrId, "修改项目基站", "1", "2");
                             throw new SmsException("导入基站信息出现异常");
                         }
                     }
                }else{
                	log.error("基站编码格式校验有误");
                	commonService.createSmsOperLog("3",mgrId, "修改项目基站", "1", "2");
                	throw new SmsException("基站编码格式错误，请重新导入");
                }
            }
        }
    	commonService.createSmsOperLog("3", mgrId,"修改项目基站信息,项目编码："+mgrId+",导入基站数量为："+stationNum, "0","2" );

        List<Integer> result = new ArrayList();
        result.add(regionList.size());
        result.add(stationNum);
        return result;
    }
}